/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.jms;

import java.util.StringTokenizer;

import javax.jms.InvalidSelectorException;
import javax.jms.JMSException;
/**
   This class verifies if the topic/message selector that are specified
   correspond to the <tag,value> pairs that are specified by the system. 
   The present system, at present, handles only equaliy tests specified in
   the tag=value style. Future work will extend this to include various other
   selection criteria's such as <b> >, <, >=, <=, !</b>.
   
   @author Shrideep Pallickara
   $Revision$
   $Date$
*/

public class JmsTopicAndSelectorVerifier implements JmsDebugFlags {
  
  /** A list of reserved keywords that are not allowed */
  private static final String[] reservedKeywords = 
  {"if", "and", "not", "or", "true", "false"};
  
  /** This is the list of selectors that we allow, and these shouldn't be
      used in topic names. Leads to parsing issues */
  private static final String[] selectorList = {"!", "|", "&", "+",   
						">", "<", "=", ",", "*"};
  
  public static void processTopicName(String name) throws JMSException {
    /** Trim whitespace from the topic name */
    name.trim();
    String exceptionInfo = "The specified topic name (" + name + ") ";
    if (name == null) 
      throw new JMSException(exceptionInfo + "is null");
    if (name.length() == 0)
      throw new JMSException(exceptionInfo + "is of length zero");
    /** Test to see if it is a reserved key word */
    for (int i=0; i < reservedKeywords.length; i++) {
      if (name.equals(reservedKeywords[i])) {
	throw new JMSException(exceptionInfo + "is a reserved key in the " +
			       " selector list");
      }/*if*/
    }/*for*/	  
    
    /** Lets get the first charachter in the property string */
    String firstChar = name.substring(0,1);
    for (int i=0; i < selectorList.length; i++) {
      if (firstChar.equals(selectorList[i])) {
	throw new JMSException(exceptionInfo + "starts with (" + firstChar +
			       ") a reserved key in the selector list");
      }/*if*/
    }/*for*/
  }/*end-method*/
  
  

  public static String checkTagValuePairs(String name) throws JMSException {
    StringTokenizer tok = new StringTokenizer(name, ",");
    int i=0;
    String formattedString="";
    String tag;
    String value;
    if (JmsTopicAndSelectorVerifier_Debug)
      System.out.print("TagValue Pair ");
    while (tok.hasMoreTokens()) {
      i++;
      if (i>1)
	formattedString += ",";
      String tagValuePair = tok.nextToken();
      if (JmsTopicAndSelectorVerifier_Debug)
	System.out.println("  ("+ i + ")->" + tagValuePair);
      StringTokenizer tok2 = new StringTokenizer(tagValuePair, "=");
      if(tok2.countTokens() == 2) {
	/** Retrieve tokens and eliminate white space. */
	tag = tok2.nextToken().trim(); 
	value = tok2.nextToken().trim();
	formattedString += (tag + "=" + value);
	if (JmsTopicAndSelectorVerifier_Debug) {
	  System.out.println("tag=value pair =" + tag + "=" + value);
	}
      } else {
	if (JmsTopicAndSelectorVerifier_Debug) {
	  System.out.println("Malformed TAG=VALUE Pair in topic/selector " 
			     + name);
	}
	throw new InvalidSelectorException("Malformed TAG=VALUE Pair in " +
					   "topic/selector " + name);
      }/*end-if*/
    }/*end-while*/
    if (JmsTopicAndSelectorVerifier_Debug) {
      System.out.println("\n" + "The original string was " + name + 
			 "\n" + "The newly formatted one " + formattedString);
    }
    return formattedString;
  }
  
  /** The number of <tag-value> pairs contained in the selector could be less 
      than the number of pairs contained in the topic. However the tags and 
      the sequence in which they are specified in crucial. Furthermore, we the
      only selectors we allow presently are wild-cards  */
  public static void verifySelectorSpecifiedOnTopic(String topicString,
						    String messageSelector) 
    throws JMSException {
    StringTokenizer topicTok = new StringTokenizer(topicString, ",");
    StringTokenizer selectorTok = new StringTokenizer(messageSelector, ",");
    
    String topicTag, selectorTag;
    String topicValue, selectorValue;

    int topicTokens = topicTok.countTokens();
    int selectorTokens = selectorTok.countTokens();
    
    /** This variable indicates the number of tags that we need to match */
    int tokensToMatch = 0;

    if (topicTokens <= selectorTokens)
      tokensToMatch = topicTokens;
    else 
      tokensToMatch = selectorTokens;
    
    for (int i=0; i < tokensToMatch; i++) {
      String topicTVPair = topicTok.nextToken(); /** topic tag-value pair*/
      String selectorTVPair = selectorTok.nextToken();
      StringTokenizer tvTokOne = new StringTokenizer(topicTVPair, "=");
      StringTokenizer tvTokTwo = new StringTokenizer(selectorTVPair, "=");

      topicTag = tvTokOne.nextToken().trim();
      selectorTag = tvTokTwo.nextToken().trim();
      if (!topicTag.equals(selectorTag))
	throw 
	  new InvalidSelectorException("The order of the tags in the Topic " +
				       "and Selector do not match at pair (" +
				       (i+1) + ") => <" + topicTag + "> != <" + 
				       selectorTag + ">");
    }/** end-for */
  } 

  public static void main(String[] args) {
    String toVerify = " Apples = Oranges, Sports = NBA   , Players  = Jordan";
    String selector1 = " Apples = ABC, Sports=NBA";
    String selector2 = " Apples = *, Sport=NBA";
    try {
      JmsTopicAndSelectorVerifier.processTopicName(toVerify);
      JmsTopicAndSelectorVerifier.checkTagValuePairs(toVerify);
      JmsTopicAndSelectorVerifier.verifySelectorSpecifiedOnTopic(toVerify, 
								 selector1);
      JmsTopicAndSelectorVerifier.verifySelectorSpecifiedOnTopic(toVerify, 
								 selector2);
    } catch (JMSException jmsEx) {
      System.out.println(jmsEx);
    }
   
  }/*end-main*/


}/*end-class */







